<style rel="stylesheet/scss" lang="scss" scoped>
  .dashboard {
    &-container {
      padding: 30px;
      height: 100%;
      .main-text{
        margin-top: 20px;
        height: 40%;
      }
      .card{
        text-align: center;
        height:calc(100vh - 650px);
        .content{
          font-size: 38px;
          margin-bottom: 20px;
        }
      }
    }
    &-text {
      font-size: 30px;
      line-height: 46px;
    }

    .clearfix:before,
    .clearfix:after {
      display: table;
      content: "";
    }
    .clearfix:after {
      clear: both
    }
  }
  .my-chart{
    height: 100%;
  }
</style>
<template>
  <div class="dashboard-container" v-loading.body="listLoading" element-loading-text="Loading">
    <el-row :gutter="20" style="height: calc(60% - 40px)">
      <el-col :span="8" style="height: 100%">
        <el-card class="box-card" style="height: 100%">
          <div slot="header" class="clearfix">
            <span>设备总览</span>
            <el-button style="float: right; padding: 3px 0" type="text"><router-link to="/report/device">更多</router-link></el-button>
          </div>
          <div id="myCahrt" ref="myCahrt" class="my-chart"></div>
        </el-card>
      </el-col>
      <el-col :span="8" style="height: 100%">
        <el-card class="box-card" style="height: 100%">
          <div slot="header" class="clearfix">
            <span>警情类型总览</span>
            <el-button style="float: right; padding: 3px 0" type="text"><router-link to="/report/warningtable">更多</router-link></el-button>
          </div>
          <div id="myCahrt2" ref="myCahrt2" class="my-chart"></div>
        </el-card>
      </el-col>
      <el-col :span="8" style="height: 100%">
        <el-card class="box-card" style="height: 100%">
          <div slot="header" class="clearfix">
            <span>警情状态总览</span>
            <el-button style="float: right; padding: 3px 0" type="text"><router-link to="/report/warningtable">更多</router-link></el-button>
          </div>
          <div id="myCahrt3" ref="myCahrt3" class="my-chart"></div>
        </el-card>
      </el-col>
     </el-row>
    <el-row :gutter="20" class="main-text">
      <el-col :span="5" style="height: 100%">
        <el-card class="box-card" style="height: 100%">
          <div slot="header" class="clearfix">
            <span>用户总数</span>
            <el-button style="float: right; padding: 3px 0" type="text"></el-button>
          </div>
          <div class="card">
            <div class="content">{{totalUserCount}}人</div>
            <div class="grow">今日新增{{addedUserCount}}人</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6" style="height: 100%">
        <el-card class="box-card" style="height: 100%">
          <div slot="header" class="clearfix">
            <span>行驶总里程</span>
            <el-button style="float: right; padding: 3px 0" type="text"><router-link to="/report/device">更多</router-link></el-button>
          </div>
          <div class="card">
            <div class="content">{{totalDistance}}km</div>
            <div class="grow">今日新增{{todayDistance}}km</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="5" style="height: 100%">
        <el-card class="box-card" style="height: 100%">
          <div slot="header" class="clearfix">
            <span>超速总次数</span>
            <el-button style="float: right; padding: 3px 0" type="text"><router-link to="/report/overspeedtable">更多</router-link></el-button>
          </div>
          <div class="card">
            <div class="content">{{totalOverspeedCount}}次</div>
            <div class="grow">今日新增{{todayOverspeedCount}}次</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8" style="height: 100%">
        <el-card class="box-card" style="height: 100%">
          <div slot="header" class="clearfix">
            <span>最新警情</span>
            <el-button style="float: right; padding: 3px 0" type="text"><router-link to="/report/warningtable">更多</router-link></el-button>
          </div>
          <div class="warninginfo" id="demo">
            <ul id="demo1">
            </ul>
            <div id="demo2"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
let echarts = require('echarts/lib/echarts');
require('echarts/lib/chart/pie');
require('echarts/lib/component/tooltip');
require('echarts/lib/component/toolbox');
require('echarts/lib/component/legend');
require('echarts/lib/component/markLine');
import resize from './mixins/resize'
import { countTracker , queryUserOvew ,lastwarning} from '@/api/request'
import moment from 'moment'
export default {
  mixins: [resize],
  name: 'dashboard',
  computed: {
    ...mapGetters([
      'name',
      'roles'
    ])
  },
  data() {
  return {
    listLoading:true,
    countdata:{},
    countuser:{},
    myCahrt:'myCahrt',
    mydata1:['在线', '离线','休眠'],
    color1:["#068e16","#ccc","#fada03"],
    values1:[],
    mydata2:['电子围栏报警','移动报警','断电报警','震动报警'],
    color2:["#5240ff","#40bfff",'#33ff99','#FF8C00'],
    values2:[
      {value:335, name:'震动报警'},
      {value:310, name:'移动报警'},
      {value:234, name:'断电报警'}
    ],
    mydata3:['已处理', '未处理'],
    color3:["#ffb726","#8c26ff"],
    values3:[
      {value:335, name:'已处理'},
      {value:310, name:'未处理'}
    ],
    timer: null,
    totalUserCount:0,
    addedUserCount:0,
    totalDistance:0,
    todayDistance:0,
    totalOverspeedCount:0,
    todayOverspeedCount:0
   }
  },

  methods:{
    /**@统计设备**/
    countTtrackers(){
      this.listLoading=true
      countTracker().then( response => {
        let count = this.countdata = response.body;
        this.totalDistance=(count.totalDistance/1000).toLocaleString()
        this.todayDistance=(count.todayDistance/1000).toLocaleString()
        this.totalOverspeedCount=count.totalOverspeedCount.toLocaleString()
        this.todayOverspeedCount=count.todayOverspeedCount.toLocaleString()

        let values1=[
          {value:count.onlineCount, name:'在线'},
          {value:count.offlineCount, name:'离线'},
          {value:count.sleepCount, name:'休眠'}
        ]
        let chart = echarts.init(this.$refs.myCahrt);
        let values2=[
          {value:count.elecfenceWarningCount, name:'电子围栏报警'},
          {value:count.movedWarningCount, name:'移动报警'},
          {value:count.powerOffWarningCount, name:'断电报警'},
          {value:count.quakeWarningCount, name:'震动报警'}
        ]
        let chart2 = echarts.init(this.$refs.myCahrt2);
        let values3=[
          {value:count.warningHandledCount, name:'已处理'},
          {value:count.warningUnhandledCount, name:'未处理'}
        ]
        let chart3 = echarts.init(this.$refs.myCahrt3);
        this.initvalues(chart,values1,this.mydata1,'设备总览',this.color1)
        this.initvalues(chart2,values2,this.mydata2,'报警类型',this.color2)
        this.initvalues(chart3,values3,this.mydata3,'报警类型',this.color3)
        this.listLoading=false
      })
    },
    initvalues (chart,values,data,title,color) {
      chart.setOption({
        tooltip : {
          trigger: 'item',
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          padding:2,
          orient: 'vertical',
          left: 'left',
          data: data,
          formatter: function(name) {
            var index = 0
            values.forEach(function(value, i) {
              if (value.name == name) {
                index = i
              }
            })
            return name + '    ' + values[index].value + '个'
          }
        },
        series : [
          {
            name:title,
            type: 'pie',
            radius : '55%',
            center: ['50%', '70%'],
            color:color,
            data:values,
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      });
    },
    countusers(){
      this.listLoading = true
      queryUserOvew().then(response => {
        if(response && response.body){
          this.countuser = response.body
          this.totalUserCount=this.countuser.totalUserCount.toLocaleString()
          this.addedUserCount=this.countuser.addedUserCount.toLocaleString()
        }else {
          this.countuser ={}

        }
        this.listLoading = false
      })
    },
    initScroll(warnings) {
      if (warnings.length > 0) {
        this.timer && clearInterval(this.timer)
        let str = ''
        for (let i = 0; i < warnings.length; i++) {
          let warningTime = ''
          if (warnings[i].warningTime) warningTime = moment(warnings[i].warningTime).format('YYYY-MM-DD HH:mm:ss')
          str += `<li className="db vh" >
          <span>${warningTime}</span>
          <span>${warnings[i].type == 0?'震动报警':warnings[i].type==3?'断电报警':warnings[i].type==5?'电子围栏报警':'移动报警'}</span>
          <span>${warnings[i].number}</span>
          <span>${warnings[i].telephone}</span>
        </li>`
        }
        document.getElementById('demo1').innerHTML = str
      }
      var speed = 35
      const that = this
      const demo = document.getElementById('demo')
      const demo2 = document.getElementById('demo2')
      const demo1 = document.getElementById('demo1')
      demo2.innerHTML = demo1.innerHTML
      function Marquee() {
        if (demo.scrollTop >= demo1.offsetHeight) {
          demo.scrollTop = 0
        } else {
          demo.scrollTop++
        }
      }
      that.timer = setInterval(() => { Marquee() }, speed)
      demo.onmouseover = function() { that.timer && clearInterval(that.timer) }
      demo.onmouseout = function() {
        that.timer = setInterval(() => { Marquee() }, speed)
      }
    },
    getlastwarning() {
      const that = this
      lastwarning().then(response => {
        if (response.body) {
          that.initScroll(response.body)
        }
      })
    }
  },
  mounted(){
    this.countTtrackers()
    this.countusers()
    this.getlastwarning()


    let test = [{
      "id": 1,
      "parentId": 0,
      "remark": "首页"
    },
      {
        "id": 2,
        "parentId": 0,
        "remark": "监控"
      },
      {
        "id": 3,
        "parentId": 0,
        "remark": "统计报表"
      },
      {
        "id": 4,
        "parentId": 0,
        "remark": "系统管理"
      },
      {
        "id": 31,
        "parentId": 3,
        "remark": "设备台账"
      },
      {
        "id": 32,
        "parentId": 3,
        "remark": "超速报表"
      },
      {
        "id": 33,
        "parentId": 3,
        "remark": "报警报表"
      },
      {
        "id": 34,
        "parentId": 3,
        "remark": "行驶热力图"
      },
      {
        "id": 35,
        "parentId": 3,
        "remark": "服务费"
      },
      {
        "id": 41,
        "parentId": 4,
        "remark": "设备管理"
      },
      {
        "id": 42,
        "parentId": 4,
        "remark": "系统用户管理"
      },
      {
        "id": 43,
        "parentId": 4,
        "remark": "乐骑卫士用户管理"
      },
      {
        "id": 44,
        "parentId": 4,
        "remark": "乐骑卫士管理员"
      },
      {
        "id": 45,
        "parentId": 4,
        "remark": "商品列表"
      },
      {
        "id": 46,
        "parentId": 4,
        "remark": "系统权限管理"
      },
      {
        "id": 331,
        "parentId": 33,
        "remark": "报警统计"
      },
      {
        "id": 332,
        "parentId": 33,
        "remark": "报警记录"
      },
      {
        "id": 461,
        "parentId": 46,
        "remark": "角色管理",
        "sort": 2,
        "url": ""
      },
      {
        "id": 462,
        "parentId": 46,
        "remark": "权限管理",
        "sort": 2,
        "url": ""
      },
      {
        "id": 4611,
        "parentId": 461,
        "remark": "添加角色"
      }
    ]


    function toTree(data) {
      // 删除 所有 children,以防止多次调用
      data.forEach(function (item) {
        delete item.children;
      });

      // 将数据存储为 以 id 为 KEY 的 map 索引数据列
      var map = {};
      data.forEach(function (item) {
        map[item.id] = item;
      });
//        console.log(map);
      var val = [];
      data.forEach(function (item) {
        // 以当前遍历项，的pid,去map对象中找到索引的id
        var parent = map[item.parentId];
        // 好绕啊，如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
        if (parent) {
          (parent.children || ( parent.children = [] )).push(item);
        } else {
          //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
          val.push(item);
        }
      });
      console.log(val)
      return val;

    }

    toTree(test)



    let tree = {
      value: 0,
      children: [{
        value: 11,
        children: [{
          value: 21,
          children: [{
            value: 31,
            children: []
          }, {
            value: 32,
            children: []
          }, {
            value: 33,
            children: []
          }]
        }, {
          value: 22,
          children: []
        }]
      }, {
        value: 12,
        children: [{
          value: 23,
          children: []
        }, {
          value: 24,
          children: []
        }]
      }, {
        value: 13,
        children: []
      }]
    }




    var recursiveTraverse = function (node, action) {
      if (!node || !node.children) { return; }
      action(node.value);
      node.children.forEach(function(item, index) {
        recursiveTraverse(item, action);
      });
    }
// 递归实现
    recursiveTraverse(tree, console.log);




  }
}
</script>

